package com.java.hohenheim.springplatform.web.security.authorize;

import com.java.hohenheim.springplatform.db.entity.RoleEntity;
import com.java.hohenheim.springplatform.db.entity.UserRoleWithRole;
import com.java.hohenheim.springplatform.web.jwt.UserToken;
import com.java.hohenheim.springplatform.web.service.AccountService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

/**
 * @author Hohenheim
 * @date 2020/9/4
 * @description 用户授权领域
 */
@Component
@Slf4j
public class UserAuthorizationRealm extends AuthorizingRealm {
    @Autowired
    private AccountService mAccountService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UserAuthorization;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        UserToken userToken = (UserToken) principalCollection.getPrimaryPrincipal();
        UserRoleWithRole userRole = mAccountService.getUserRoles(userToken.getUserId());

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        if(null!=userRole && null!=userRole.getRoleList()) {
            ArrayList<String> roleNameList = new ArrayList<>();
            for (RoleEntity roleEntity : userRole.getRoleList()) {
                roleNameList.add(roleEntity.getRoleName());
            }
            authorizationInfo.addRoles(roleNameList);
        }

        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UserToken userToken = (UserToken) authenticationToken.getPrincipal();
        return new SimpleAuthenticationInfo(userToken, authenticationToken.getCredentials(), getName());
    }
}